<?php
/**
 * 点大商城（www.diandashop.com） - 微信公众号小程序商城系统!
 * Copyright © 2020 山东点大网络科技有限公司 保留所有权利
 * =========================================================
 * 版本：V2
 * 授权主体：shop.guanjunbang.cn
 * 授权域名：shop.guanjunbang.cn
 * 授权码：vdcajlVLIVAgVdkfJvgY
 * ----------------------------------------------
 * 您只能在商业授权范围内使用，不可二次转售、分发、分享、传播
 * 任何企业和个人不得对代码以任何目的任何形式的再发布
 * =========================================================
 */

namespace app\controller;
use think\facade\Db;

class ApiIndex extends ApiCommon {
	//自定义页面
	public function index() {
		$pid = input('param.pid/d');
		if (getcustom('plug_businessqr') && $this->member['bid']) {
			$needgoto = true;
			$business = Db::name('business')->where('aid', aid)->where('id', $this->member['bid'])->where('status', 1)->find();
			if (!$business) {
				$needgoto = false;
			} elseif ($business['start_hours'] != $business['end_hours']) {
				$start_time = strtotime(date('Y-m-d ' . $business['start_hours']));
				$end_time = strtotime(date('Y-m-d ' . $business['end_hours']));
				if (($start_time < $end_time && ($start_time > time() || $end_time < time())) || ($start_time >= $end_time && ($start_time > time() && $end_time < time()))) {
					$needgoto = false;
				}
			}
			if ($needgoto) {
				$pagedata = Db::name('designerpage')->where('aid', aid)->where('bid', $this->member['bid'])->where('ishome', 1)->find();
				if (!$pagedata) {
					die(jsonEncode(['status' => -3, 'url' => '/pages/shop/fastbuy2?bid=' . $this->member['bid']]));
				} else {
					die(jsonEncode(['status' => -3, 'url' => '/pages/businsess/index?id=' . $this->member['bid']]));
				}
			}
		}
		if (getcustom('plug_tengrui')) {
			if ($this->member) {
				//全部同步认证
				$tengrui = new \app\custom\TengRui(aid, mid);
				$tengrui->tb_dan_member($this->member['mpopenid']);
			}
		}
		$sysset = Db::name('admin_set')->field('name,logo,desc,tel,gzts,ddbb,ddbbtourl,mode,address')->where('aid', aid)->find();

		if (getcustom('loc_business') && $sysset['mode'] == 1) {
			//场景1：已选店铺
			$select_bid = input('param.select_bid/d');
			if ($select_bid) {
				return (new ApiBusiness($this->app))->index($select_bid);
			}
			//场景2：未选店铺，传递坐标，默认最近店铺
			$latitude = input('param.latitude');
			$longitude = input('param.longitude');
			if ($longitude && $longitude) {
				$where = [];
				$where[] = ['aid', '=', aid];
				$where[] = ['status', '=', 1];
				$where[] = ['is_open', '=', 1];
				$order = Db::raw("({$longitude}-longitude)*({$longitude}-longitude) + ({$latitude}-latitude)*({$latitude}-latitude) ");
				$business = Db::name('business')->fieldRaw('id,name,logo,address,comment_score,sales,content,longitude,latitude')->where($where)->order($order)->find();
				return (new ApiBusiness($this->app))->index($business['id']);
			}

			$rdata = [];
			$rdata['status'] = 1;
			$rdata['needlocation'] = true;
			$rdata['guanggaopic'] = '';
			$rdata['guanggaourl'] = '';
			$rdata['pageinfo'] = [];
			$rdata['pagecontent'] = [];
			$rdata['issubscribe'] = $this->member['subscribe'];
			$rdata['sysset'] = $sysset;
			$rdata['oglist'] = false;
			$rdata['copyright'] = Db::name('admin')->where('id', aid)->value('copyright');
			return $this->json($rdata);

		}

		$pageid = input('param.id/d');
		$where = [];
		$where[] = ['aid', '=', aid];
		if (!$pageid) {
			$where[] = ['ishome', '=', 1];
			$where[] = ['bid', '=', 0];
		} else {
			$where[] = ['id', '=', $pageid];
		}
		$pagedata = Db::name('designerpage')->where($where)->find();
		if (!$pagedata) {
			return $this->json(['status' => 0, 'msg' => '页面不存在']);
		}
		$latitude = input('param.latitude');
		$longitude = input('param.longitude');
		$area = input('param.area', '');

		$pageinfo = json_decode($pagedata['pageinfo'], true);
		$pagecontent = json_decode(\app\common\System::initpagecontent($pagedata['content'], aid, mid, platform, $latitude, $longitude, $area), true);

		$needlocation = false;
		if (!$latitude || !$longitude) {
			foreach ($pagecontent as $item) {
				if ($item['temp'] == 'business' && ($item['params']['sortby'] == 'juli' || $item['params']['showdistance'])) {
					$needlocation = true;
				}
				if ($item['temp'] == 'form' && $item['data']['fanwei'] == 1) {
					$needlocation = true;
				}
				if ($item['temp'] == 'product' && $item['params']['sortby'] == 'juli') {
					$needlocation = true;
				}
			}
		} else {
			
			foreach ($pagecontent as $item) {
				if ($item['temp'] == 'form' && $item['data']['fanwei'] == 1) {
					//判断表单是否超出范围
					$juli = getdistance($longitude, $latitude, $item['data']['fanwei_lng'], $item['data']['fanwei_lat'], 1);
					if ($juli > $item['data']['fanwei_range']) {
						return $this->json(['status' => 0, 'msg' => '请在指定范围内使用']);
					}
				}
			}
		}
		$pageparams = $pageinfo[0]['params'];
		if ($pagedata['ishome'] == 0 && $pageparams['quanxian']) {
			if (!$pageparams['quanxian']['all'] && !$pageparams['quanxian'][$this->member['levelid']]) {
				if ($pageparams['quanxian']['gly']) {
					//管理员可查看
					$uid = cache($this->sessionid . '_uid');
					if (!$uid) {
						if ($this->member) {
							$uid = Db::name('admin_user')->where('aid', aid)->where('mid', mid)->value('id');
						}
						if (!$uid) {
							return $this->json(['status' => 0, 'msg' => $pageparams['quanxiantips'], 'url' => $pageparams['hrefurl2']]);
						}
					}
				} else {
					return $this->json(['status' => 0, 'msg' => $pageparams['quanxiantips'], 'url' => $pageparams['hrefurl2']]);
				}
			}
		}
		if ($pageparams['fufei'] == 1 && floatval($pageparams['money']) > 0) {
			//付费查看
			$hasff = Db::name('designerpage_order')->where('aid', aid)->where('pageid', $pagedata['id'])->where('mid', mid)->where('status', 1)->find();
			if (!$hasff) {
				$adata = array();
				$adata['aid'] = aid;
				$adata['bid'] = $pagedata['bid'];
				$adata['pageid'] = $pagedata['id'];
				$adata['mid'] = mid;
				$adata['title'] = $pageparams['title'];
				$adata['price'] = floatval($pageparams['money']);
				$adata['ordernum'] = date('ymdHis') . aid . rand(1000, 9999);
				$adata['createtime'] = time();
				$orderid = Db::name('designerpage_order')->insertGetId($adata);
				$payorderid = \app\model\Payorder::createorder(aid, $adata['bid'], $adata['mid'], 'designerpage', $orderid, $adata['ordernum'], $adata['title'], $adata['price']);
				return $this->json(['status' => 2, 'msg' => '需要付费查看', 'orderid' => $orderid, 'payorderid' => $payorderid]);
			}
		}

		$guanggaopic = '';
		$guanggaourl = '';
		if ($pageparams['showgg'] == 1) {
			$showgg = 0;
			if ($pageparams['ggrenqun']) {
				if ($pageparams['ggrenqun']['0']) {
					$showgg = 1;
				}
				if ($pageparams['ggrenqun']['-1'] && $this->member['subscribe'] == 1) {
					$showgg = 1;
				}
				if ($pageparams['ggrenqun']['-2'] && $this->member['subscribe'] != 1) {
					$showgg = 1;
				}
				if ($showgg == 0 && $pageparams['ggrenqun'][$this->member['levelid']]) {
					$showgg = 1;
				}
			}
			if ($showgg == 1 && $pageparams['cishu'] == 0 && $this->member) {
				$hasshowlog = Db::name('guanggao_showlog')->where('mid', mid)->where('platform', platform)->where('pic', $pageparams['guanggao'])->find();
				if ($hasshowlog) {
					$showgg = 0;
				} else {
					Db::name('guanggao_showlog')->insert(['aid' => aid, 'mid' => mid, 'pic' => $pageparams['guanggao'], 'platform' => platform, 'createtime' => time()]);
				}
			}
			if ($showgg) {
				$guanggaopic = $pageparams['guanggao'];
				$guanggaourl = $pageparams['hrefurl'];
			}
		}
		$sysset['showgzts'] = false;
		if (platform == 'mp') {
			$sysset['gzts'] = explode(',', $sysset['gzts']);
			if (in_array('1', $sysset['gzts']) && $this->member['subscribe'] == 0) {
				$appinfo = \app\common\System::appinfo(aid, 'mp');
				$sysset['qrcode'] = $appinfo['qrcode'];
				$sysset['gzhname'] = $appinfo['nickname'];
				$sysset['showgzts'] = true;
			}
		}
		//订单播报
		$oglist = [];
		$sysset['ddbb'] = explode(',', $sysset['ddbb']);
		if (in_array('1', $sysset['ddbb'])) {
			$oglist1 = Db::name('shop_order_goods')->field('mid,name,createtime,proid')->where('aid', aid)->where('status', 'in', '0,1,2,3')->where('createtime', '>', time() - 86400 * 10)->order('createtime desc')->limit(10)->select()->toArray();
			if (!$oglist1) {
				$oglist1 = [];
			}

			foreach ($oglist1 as $k => $og) {
				$og['type'] = 'shop';
				if ($sysset['ddbbtourl']) {
					$og['tourl'] = $sysset['ddbbtourl'];
				} else {
					$og['tourl'] = '/pages/shop/product?id=' . $og['proid'];
				}
				$ogmember = Db::name('member')->where('id', $og['mid'])->find();
				if (!$ogmember) {
					unset($og);
					continue;
				} else {
					$og['nickname'] = $ogmember['nickname'];
					$og['headimg'] = $ogmember['headimg'];
				}
				if (time() - $og['createtime'] < 60 * 5) {
					$og['showtime'] = '刚刚';
				} elseif (date('Ymd') == date('Ymd', $og['createtime'])) {
					if ($og['createtime'] + 3600 > time()) {
						$og['showtime'] = floor((time() - $og['createtime']) / 60) . '分钟前';
					} else {
						$og['showtime'] = floor((time() - $og['createtime']) / 3600) . '小时前';
					}
				} elseif (time() - $og['createtime'] < 86400) {
					$og['showtime'] = '昨天';
				} elseif (time() - $og['createtime'] < 2 * 86400) {
					$og['showtime'] = '前天';
				} else {
					$og['showtime'] = '三天前';
				}
				$oglist[] = $og;
			}
		}
		if (in_array('3', $sysset['ddbb'])) {
			$oglist2 = Db::name('collage_order')->field('mid,title name,createtime,proid,buytype')->where('aid', aid)->where('status', 'in', '0,1,2,3')->where('createtime', '>', time() - 86400 * 10)->order('createtime desc')->limit(6)->select()->toArray();
			if (!$oglist2) {
				$oglist2 = [];
			}

			foreach ($oglist2 as $k => $og) {
				$og['type'] = 'collage';
				if ($sysset['ddbbtourl']) {
					$og['tourl'] = $sysset['ddbbtourl'];
				} else {
					$og['tourl'] = '/activity/collage/product?id=' . $og['proid'];
				}
				$ogmember = Db::name('member')->where('id', $og['mid'])->find();
				if (!$ogmember) {
					unset($og);
					continue;
				} else {
					$og['nickname'] = $ogmember['nickname'];
					$og['headimg'] = $ogmember['headimg'];
				}
				if (time() - $og['createtime'] < 60 * 5) {
					$og['showtime'] = '刚刚';
				} elseif (date('Ymd') == date('Ymd', $og['createtime'])) {
					if ($og['createtime'] + 3600 > time()) {
						$og['showtime'] = floor((time() - $og['createtime']) / 60) . '分钟前';
					} else {
						$og['showtime'] = floor((time() - $og['createtime']) / 3600) . '小时前';
					}
				} elseif (time() - $og['createtime'] < 86400) {
					$og['showtime'] = '昨天';
				} elseif (time() - $og['createtime'] < 2 * 86400) {
					$og['showtime'] = '前天';
				} else {
					$og['showtime'] = '三天前';
				}
				$oglist[] = $og;
			}
		}
		if (in_array('4', $sysset['ddbb'])) {
			$oglist3 = Db::name('seckill_order')->field('mid,title name,createtime,proid')->where('aid', aid)->where('status', 'in', '0,1,2,3')->where('createtime', '>', time() - 86400 * 10)->order('createtime desc')->limit(6)->select()->toArray();
			if (!$oglist3) {
				$oglist3 = [];
			}

			foreach ($oglist3 as $k => $og) {
				$og['type'] = 'seckill';
				if ($sysset['ddbbtourl']) {
					$og['tourl'] = $sysset['ddbbtourl'];
				} else {
					$og['tourl'] = '/activity/seckill/product?id=' . $og['proid'];
				}
				$ogmember = Db::name('member')->where('id', $og['mid'])->find();
				if (!$ogmember) {
					unset($og);
					continue;
				} else {
					$og['nickname'] = $ogmember['nickname'];
					$og['headimg'] = $ogmember['headimg'];
				}
				if (time() - $og['createtime'] < 60 * 5) {
					$og['showtime'] = '刚刚';
				} elseif (date('Ymd') == date('Ymd', $og['createtime'])) {
					if ($og['createtime'] + 3600 > time()) {
						$og['showtime'] = floor((time() - $og['createtime']) / 60) . '分钟前';
					} else {
						$og['showtime'] = floor((time() - $og['createtime']) / 3600) . '小时前';
					}
				} elseif (time() - $og['createtime'] < 86400) {
					$og['showtime'] = '昨天';
				} elseif (time() - $og['createtime'] < 2 * 86400) {
					$og['showtime'] = '前天';
				} else {
					$og['showtime'] = '三天前';
				}
				$oglist[] = $og;
			}
		}
		$oglistpx = array_column($oglist, 'createtime');
		array_multisort($oglistpx, SORT_DESC, $oglist);

		if (!$pageparams['bgcolor']) {
			$pageparams['bgcolor'] = '#f7f7f8';
		}
		if (getcustom('agent_card')) {
			$agentCard = Db::name('admin_set')->where('aid', aid)->value('agent_card');
			if ($agentCard == 1) {
				$agentCard2 = Db::name('admin')->where('id', aid)->value('agent_card');
				if ($agentCard2 == 1) {
					$sysset['agent_card'] = 1;
					$sysset['agent_card_info'] = $this->getAgentCard($pid);
				}
			}
		}

		$sysset['ddbb_position'] = 'top';
		if (getcustom('ngmm')) {
			$sysset['ddbb_position'] = 'bottom';
		}

		$rdata = [];
		$rdata['status'] = 1;
		$rdata['needlocation'] = $needlocation;
		$rdata['guanggaopic'] = $guanggaopic;
		$rdata['guanggaourl'] = $guanggaourl;
		$rdata['pageinfo'] = $pageparams;
		$rdata['pagecontent'] = $pagecontent;
		//dump($pagecontent);die;
		$rdata['issubscribe'] = $this->member['subscribe'];
		$rdata['sysset'] = $sysset;
		$rdata['oglist'] = $oglist ? $oglist : false;
		$rdata['copyright'] = Db::name('admin')->where('id', aid)->value('copyright');
		if (getcustom('xixie')) {
			$xixie_sysset = Db::name('xixie_sysset')->where('aid', aid)->find();
			//洗鞋标志
			$rdata['xixie'] = false;
			$rdata['xdata'] = '';
			if ($xixie_sysset && $xixie_sysset['all_close'] == 0) {
				$rdata['xixie'] = true;
				$rdata['xdata'] = \app\custom\Xixie::get_xixie_data(aid, $this->member, $xixie_sysset);
			}
		}
		return $this->json($rdata);
	}
	//获取tab选项卡数据
	public function gettabcontent() {
		$where = [];
		$where[] = ['aid', '=', aid];
		$where[] = ['tabid', '=', input('post.tabid')];
		$where[] = ['tabindexid', '=', input('post.tabindexid')];
		$pagedata = Db::name('designerpage_tab')->where($where)->find();
		if (!$pagedata) {
			return $this->json(['status' => 0, 'msg' => '数据不存在', 'pagecontent' => []]);
		}
		$latitude = input('param.latitude');
		$longitude = input('param.longitude');
		$area = input('param.area');
		$pagecontent = json_decode(\app\common\System::initpagecontent($pagedata['content'], aid, mid, platform, $latitude, $longitude, $area), true);

		$needlocation = false;
		if (!$latitude || !$longitude) {
			foreach ($pagecontent as $item) {
				if ($item['temp'] == 'business' && ($item['params']['sortby'] == 'juli' || $item['params']['showdistance'])) {
					$needlocation = true;
				}
				if ($item['temp'] == 'form' && $item['data']['fanwei'] == 1) {
					$needlocation = true;
				}
				if ($item['temp'] == 'product' && $item['params']['sortby'] == 'juli') {
					$needlocation = true;
				}
			}
		} else {
			foreach ($pagecontent as $item) {
				if ($item['temp'] == 'form' && $item['data']['fanwei'] == 1) {
					//判断表单是否超出范围
					$juli = getdistance($longitude, $latitude, $item['data']['fanwei_lng'], $item['data']['fanwei_lat'], 1);
					if ($juli > $item['data']['fanwei_range']) {
						return $this->json(['status' => 0, 'msg' => '请在指定范围内使用']);
					}
				}
			}
		}
		$rdata = [];
		$rdata['status'] = 1;
		$rdata['pagecontent'] = $pagecontent;
		$rdata['needlocation'] = $needlocation;
		return $this->json($rdata);
	}
	//登录
	public function login() {
		$sysset = Db::name('admin_set')->where('aid', aid)->find();
		$platform = platform;
		$logintype = $sysset['logintype_' . $platform];
		$logintype = explode(',', $logintype);

		$xieyi = Db::name('admin_set_xieyi')->where('aid', aid)->find();
		if (!$xieyi) {
			$xieyi = ['status' => 0, 'content' => ''];
		}

		$smsset = Db::name('admin_set_sms')->where('aid', aid)->find();
		if ($smsset && $smsset['status'] == 1 && $smsset['tmpl_smscode'] && $smsset['tmpl_smscode_st'] == 1) {
			$needsms = true;
		} else {
			$needsms = false;
		}

		$pid = input('param.pid');
		if ($pid) {
			$parent = Db::name('member')->where('aid', aid)->where('id', $pid)->field('id,nickname,headimg')->find();
		}
		if ($sysset['reg_invite_code_type'] == 1) {
			$reg_invite_code_text = '邀请码';
		} else {
			$reg_invite_code_text = '手机号';
		}

		$rdata = [];
		$rdata['status'] = 1;
		$rdata['name'] = $sysset['name'];
		$rdata['logo'] = $sysset['logo'];
		$rdata['xystatus'] = $xieyi['status'];
		$rdata['xyname'] = $xieyi['name'];
		$rdata['xycontent'] = $xieyi['content'];
		$rdata['xyname2'] = $xieyi['name2'];
		$rdata['xycontent2'] = $xieyi['content2'];
		$rdata['logintype_1'] = in_array('1', $logintype); //注册登录
		$rdata['logintype_2'] = in_array('2', $logintype); //手机验证码登录
		$rdata['logintype_3'] = platform != 'h5' ? in_array('3', $logintype) : false; //授权登录 h5时去掉授权登录
		$rdata['logintype_4'] = $rdata['logintype_3']; //Apple登录
		//$rdata['logintype_3'] = in_array('3',$logintype); //授权登录 h5时去掉授权登录
		$rdata['logintype_6'] = in_array('6', $logintype); //Google登录
		$rdata['google_client_id'] = $sysset['google_client_id'];
		$rdata['platform'] = platform;
		$rdata['needsms'] = $needsms;
		$rdata['reg_invite_code'] = $sysset['reg_invite_code'];
		$rdata['reg_invite_code_text'] = $reg_invite_code_text;
		$rdata['reg_invite_code_type'] = $sysset['reg_invite_code_type'];
		$rdata['parent'] = $parent ? $parent : null;

		$rdata['login_mast'] = ($sysset['login_mast'] && in_array(platform, explode(',', $sysset['login_mast'])) ? true : false);
		if (mid) {
//			Db::name('member')->where('aid',aid)->where('session_id',$this->sessionid)->update(['session_id'=>'']);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->delete();
			cache($this->sessionid . '_mid', null);
			$this->mid = 0;
			$this->sessionid = \think\facade\Session::getId();
			$rdata['sessionid'] = $this->sessionid;
		}
		return $this->json($rdata);
	}
	public function loginsub() {
		$logintype = input('param.logintype');
		$tel = input('param.tel');
		$pwd = input('param.pwd');
		$smscode = input('param.smscode');
		$fromid = input('param.pid');
		$yqcode = input('param.yqcode');
		if ($logintype == 1) {
			//账号密码登录
			if (!$tel || !$pwd) {
				return $this->json(['status' => 0, 'msg' => '手机号或密码不能为空']);
			}
			$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->where('pwd', md5($pwd))->find();
			if (!$member) {
				return $this->json(['status' => 0, 'msg' => '手机号或密码输入错误']);
			}
			if ($member['checkst'] == 0) {
				return $this->json(['status' => 0, 'msg' => '账号审核中']);
			}

			if ($member['checkst'] == 2) {
				return $this->json(['status' => 0, 'msg' => '账号审核未通过,驳回原因:' . $member['checkreason']]);
			}

			cache($this->sessionid . '_mid', $member['id'], 7 * 86400);

//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$member['id'])->update(['session_id'=>session_id]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $member['id'],
				'login_time' => time(),
			]);
			return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $member['id'], 'session_id' => $this->sessionid]);
		}
		if ($logintype == 2) {
			//手机验证码登录
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
			$tmplids = [];
			if (!$member) {
				$data = [];
				$data['aid'] = aid;
				$data['tel'] = $tel;
				$data['nickname'] = substr($tel, 0, 3) . '****' . substr($tel, -4);
				$data['sex'] = 3;
				$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
				$data['createtime'] = time();
				$data['last_visittime'] = time();
//				$data['session_id'] = $this->sessionid;
				//推广人
				if ($fromid) {
					$data['pid'] = $this->getpid($fromid);
				} elseif ($yqcode) {
					$sysset = Db::name('admin_set')->where('aid', aid)->find();
					if ($sysset['reg_invite_code']) {
						if ($sysset['reg_invite_code_type'] == 1) { //邀请码
							//                        $upuser = Db::name('member')->where('aid',aid)->where('invite_code',$yqcode)->find();
						} elseif ($sysset['reg_invite_code_type'] == 2) {
//id
							$upuser = Db::name('member')->where('aid', aid)->where('id', intval($fromid))->find();
						} else {
//手机号
							$upuser = Db::name('member')->where('aid', aid)->where('tel', $yqcode)->find();
						}

						$uplv = Db::name('member_level')->where('aid', aid)->where('id', $upuser['levelid'])->find();
						if ($upuser && $uplv['can_agent'] != 0) {
							$data['pid'] = $upuser['id'];
						}
					}
				}
				$data['platform'] = platform;
				$mid = \app\model\Member::add(aid, $data);
				Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
					'mid' => $mid,
					'login_time' => time(),
				]);
				if ($data['pid']) {
					\app\common\Common::user_tjscore(aid, $mid);
				}

				//注册赠送
				\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
				cache($this->sessionid . '_mid', $mid, 7 * 86400);
				if (platform == 'wx' && $this->sysset['reg_check'] == 1) {
					$wx_tmplset = Db::name('wx_tmplset')->where('aid', aid)->find();
					if ($wx_tmplset['tmpl_shenhe_new']) {
						$tmplids[] = $wx_tmplset['tmpl_shenhe_new'];
					}
				}
			} else {
				$mid = $member['id'];
				cache($this->sessionid . '_mid', $member['id'], 7 * 86400);
//				if($member['session_id']){
				//					$this->sessionid = $member['session_id'];
				//				}else{
				//					Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
				//				}
				Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
					'mid' => $mid,
					'login_time' => time(),
				]);
			}
			return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid, 'tmplids' => $tmplids]);
		}
	}
	//公众号静默授权登录
	public function mpbaselogin() {
		$appinfo = \app\common\System::appinfo(aid, 'mp');
		$appid = $appinfo['appid'];
		$appsecret = $appinfo['appsecret'];

		$fromid = input('param.pid/d');
		if ($appinfo['authtype'] == 1) {
			//授权接入
			$component_appid = \app\common\Wechat::component_appid();
		}
		//授权登录
		if (input('param.state') && input('param.state') == 'baseauthlogin' && input('param.code')) {
			$code = input('param.code');
			if ($appinfo['authtype'] == 1) {
				//授权接入
				$url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid={$appid}&code={$code}&grant_type=authorization_code&component_appid={$component_appid}&component_access_token=" . \app\common\Wechat::component_access_token(aid);
			} else {
				$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
			}
			$result = request_get($url);
			$rs = json_decode($result);
			$openid = $rs->openid;
			if ($openid) {
				$result2 = request_get('https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . \app\common\Wechat::access_token(aid, 'mp') . '&openid=' . $openid . '&lang=zh_CN');
				$result = json_decode($result2, true);
				$member = Db::name('member')->where('aid', aid)->where('mpopenid', $openid)->find();
				if (!$member && $result['unionid']) {
					$member = Db::name('member')->where('aid', aid)->where('unionid', $result['unionid'])->find();
					if ($member) {
						Db::name('member')->where('id', $member['id'])->update(['mpopenid' => $openid]);
					}

				}
				if (!$member) {
					$data = [];
					$data['aid'] = aid;
					$data[platform . 'openid'] = $openid;
					if ($result['unionid']) {
						$data['unionid'] = $result['unionid'];
					}
					$data['sex'] = 3;
					$data['nickname'] = '用户' . random(6);
					$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
					$data['createtime'] = time();
					$data['last_visittime'] = time();
					//推广人
					if ($fromid) {
						$data['pid'] = $this->getpid($fromid);
					}
					$data['platform'] = platform;
					$mid = \app\model\Member::add(aid, $data);
					Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
						'mid' => $mid,
						'login_time' => time(),
					]);
					if ($data['pid']) {
						\app\common\Common::user_tjscore(aid, $mid);
					}

					//注册赠送
					\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
				} else {
					$mid = $member['id'];
					Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
						'mid' => $mid,
						'login_time' => time(),
					]);
				}
				cache($this->sessionid . '_mid', $mid, 7 * 86400);
				if (input('param.frompage') && input('param.frompage') != '/pages/index/login' && input('param.frompage') != '/pages/index/reg' && input('param.frompage') != '/pages/index/getpwd') {
					return redirect(m_url(urldecode(input('param.frompage'))));
				}
				return redirect(m_url('pages/my/usercenter'));
			} else {
				if ($rs->errcode == 40163 || $rs->errcode == 40029) {
					$request_url = $_SERVER["REQUEST_URI"];
					if (strpos($request_url, '?code=')) {
						$request_url = explode('?code=', $request_url)[0];
					} elseif (strpos($request_url, '&code=')) {
						$request_url = explode('&code=', $request_url)[0];
					}
					$redirectUrl = request()->domain() . $request_url;
					return redirect($redirectUrl);
					die;
				} else {
					return $this->json(['status' => 0, 'msg' => '授权登录失败,请重新操作']);
				}
			}
		} else {
			//获取用户信息
			$request_url = ltrim($_SERVER["REQUEST_URI"], '/');
			if (strpos($request_url, '?code=') !== false) {
				$request_url = explode('?code=', $request_url)[0];
			} elseif (strpos($request_url, '&code=') !== false) {
				$request_url = explode('&code=', $request_url)[0];
			}
			$redirectUrl = request()->domain() . '/' . $request_url; //.'&frompage='.input('param.frompage');
			//\think\facade\Log::write($redirectUrl);
			$redirectUrl = urlencode($redirectUrl);
			if ($appinfo['authtype'] == 1) {
				//授权接入
				$getUserinfoUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&component_appid={$component_appid}&redirect_uri={$redirectUrl}&response_type=code&scope=snsapi_base&state=baseauthlogin#wechat_redirect";
			} else {
				$getUserinfoUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirectUrl}&response_type=code&scope=snsapi_base&state=baseauthlogin#wechat_redirect";
			}
			return redirect($getUserinfoUrl);
		}
	}
	//公众号网页授权登录
	public function shouquan() {
		$appinfo = \app\common\System::appinfo(aid, 'mp');
		$appid = $appinfo['appid'];
		$appsecret = $appinfo['appsecret'];

		$fromid = input('param.pid/d');
		if ($appinfo['authtype'] == 1) {
			//授权接入
			$component_appid = \app\common\Wechat::component_appid();
		}
		//授权登录
		if (input('param.state') && input('param.state') == 'authlogin' && input('param.code')) {
			$code = input('param.code');
			if ($appinfo['authtype'] == 1) {
				//授权接入
				$url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid={$appid}&code={$code}&grant_type=authorization_code&component_appid={$component_appid}&component_access_token=" . \app\common\Wechat::component_access_token(aid);
			} else {
				$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
			}
			$result = request_get($url);
			$rs = json_decode($result);
			if ($rs->openid) {
				//$result = request_get('https://api.weixin.qq.com/cgi-bin/user/info?access_token='.\app\common\Wechat::access_token(aid,'mp').'&openid='.$rs->openid.'&lang=zh_CN');
				//$result = json_decode($result,true);
				//if(!$result || $result['subscribe']==0){
				$result = request_get("https://api.weixin.qq.com/sns/userinfo?access_token={$rs->access_token}&openid={$rs->openid}&lang=zh_CN");
				$result = json_decode($result, true);
				//}
				$result2 = request_get('https://api.weixin.qq.com/cgi-bin/user/info?access_token=' . \app\common\Wechat::access_token(aid, 'mp') . '&openid=' . $rs->openid . '&lang=zh_CN');
				$result2 = json_decode($result2, true);
				$result['subscribe'] = $result2['subscribe'];
				$result['subscribe_time'] = $result2['subscribe_time'];
				$member = Db::name('member')->where('aid', aid)->where('mpopenid', $result['openid'])->find();
				if (!$member && $result['unionid']) {
					$member = Db::name('member')->where('aid', aid)->where('unionid', $result['unionid'])->find();
					if ($member) {
						Db::name('member')->where('id', $member['id'])->update(['mpopenid' => $result['openid']]);
					}

				}
				if (!$member) {
					cache($this->sessionid . '_' . platform . 'UserInfo', $result, 3600);
					$info = Db::name('admin_set')->where('aid', aid)->find();
					if ($info['login_bind']) {
						$params = '?logintype=4&login_bind=' . $info['login_bind'] . '&frompage=' . input('param.frompage');
						if ($fromid) {
							$params .= '&pid=' . $fromid;
						}
						return redirect(m_url('pages/index/login' . $params));
					}
					return $this->shouquanRegister(1);
				} else {
					$mid = $member['id'];
					if (!$member['headimg'] || strpos($member['headimg'], '/static/img/touxiang.png') !== false) {
						$update = [];
						$update['nickname'] = $result['nickname'];
						$update['headimg'] = \app\common\Pic::uploadoss($result['headimgurl']);
						$update['sex'] = $result['sex'];
						$update['province'] = $result['province'];
						$update['city'] = $result['city'];
						Db::name('member')->where('id', $member['id'])->update($update);
					}

					Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
						'mid' => $mid,
						'login_time' => time(),
					]);
				}
				cache($this->sessionid . '_mid', $mid, 7 * 86400);
				if (input('param.frompage') && input('param.frompage') != '/pages/index/login' && input('param.frompage') != '/pages/index/reg' && input('param.frompage') != '/pages/index/getpwd') {
					return redirect(m_url(str_replace('amp;', '', urldecode(input('param.frompage')))));
				}
				return redirect(m_url('pages/my/usercenter'));
			} else {
				if ($rs->errcode == 40163 || $rs->errcode == 40029) {
					$request_url = $_SERVER["REQUEST_URI"];
					if (strpos($request_url, '?code=')) {
						$request_url = explode('?code=', $request_url)[0];
					} elseif (strpos($request_url, '&code=')) {
						$request_url = explode('&code=', $request_url)[0];
					}
					$redirectUrl = request()->domain() . $request_url;
					return redirect($redirectUrl);
					die;
				} else {
					return $this->json(['status' => 0, 'msg' => '授权登录失败,请重新操作']);
				}
			}
		} else {
			//获取用户信息
			$request_url = ltrim($_SERVER["REQUEST_URI"], '/');
			if (strpos($request_url, '?code=') !== false) {
				$request_url = explode('?code=', $request_url)[0];
			} elseif (strpos($request_url, '&code=') !== false) {
				$request_url = explode('&code=', $request_url)[0];
			}
			$redirectUrl = request()->domain() . '/' . $request_url; //.'&frompage='.input('param.frompage');
			//\think\facade\Log::write($redirectUrl);
			$redirectUrl = urlencode($redirectUrl);
			if ($appinfo['authtype'] == 1) {
				//授权接入
				$getUserinfoUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&component_appid={$component_appid}&redirect_uri={$redirectUrl}&response_type=code&scope=snsapi_userinfo&state=authlogin#wechat_redirect";
			} else {
				$getUserinfoUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirectUrl}&response_type=code&scope=snsapi_userinfo&state=authlogin#wechat_redirect";
			}
			return redirect($getUserinfoUrl);
		}
	}
	//公众号网页授权注册
	public function shouquanRegister($isredirect = 0) {
		$fromid = input('param.pid/d');
		$tel = input('param.tel');
		$smscode = input('param.smscode');
		$result = cache($this->sessionid . '_' . platform . 'UserInfo');
		//授权登录
		$rs = $result;
		if (!$rs['openid']) {
			return json(['status' => 0, 'msg' => '获取授权信息失败!']);
		}

		$member = Db::name('member')->where('aid', aid)->where('mpopenid', $result['openid'])->find();
		if (!$member && $result['unionid']) {
			$member = Db::name('member')->where('aid', aid)->where('unionid', $result['unionid'])->find();
			if ($member) {
				Db::name('member')->where('id', $member['id'])->update(['mpopenid' => $result['openid']]);
			}

		}
		if ($tel) {
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			if ($member) {
				$hasmember = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if (!$hasmember) {
					Db::name('member')->where('id', $member['id'])->update(['tel' => $tel]);
				} else {
					return $this->json(['status' => 0, 'msg' => '该手机号已被其他用户绑定']);
				}
			} else {
				$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if ($member) {
					$update = [];
					$update['mpopenid'] = $result['openid'];
					if ($result['unionid']) {
						$update['unionid'] = $result['unionid'];
					}
					if (!$member['headimg'] || strpos($member['headimg'], '/static/img/touxiang.png') !== false) {
						$update['nickname'] = $result['nickname'];
						$update['headimg'] = \app\common\Pic::uploadoss($result['headimgurl']);
						$update['sex'] = $result['sex'];
						$update['province'] = $result['province'];
						$update['city'] = $result['city'];
					}
					Db::name('member')->where('id', $member['id'])->update($update);
				}
			}
		}
		if (!$member) {
			$data = [];
			$data['aid'] = aid;
			$data['mpopenid'] = $result['openid'];
			$data['nickname'] = $result['nickname'];
			$data['sex'] = $result['sex'];
			$data['province'] = $result['province'];
			$data['city'] = $result['city'];
			$data['country'] = $result['country'];
			$data['headimg'] = \app\common\Pic::uploadoss($result['headimgurl']);
			$data['unionid'] = $result['unionid'];
			$data['subscribe'] = $result['subscribe'] == 1 ? 1 : 0;
			$data['subscribe_time'] = $result['subscribe_time'];
			$data['createtime'] = time();
			$data['last_visittime'] = time();
//            $data['session_id'] = $this->sessionid;
			if ($tel) {
				$data['tel'] = $tel;
			}
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($result['subscribe'] == 1 && $member['subscribe'] == 0) {
				Db::name('member')->where('id', $mid)->update(['subscribe' => 1]);
			}
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		if ($isredirect) {
			if (input('param.frompage')) {
				return redirect(m_url(urldecode(input('param.frompage'))));
			}
			return redirect(m_url('pages/my/usercenter'));
		} else {
			return json(['status' => 1, 'msg' => '登录成功']);
		}
	}
	//微信小程序授权登录
	public function wxlogin() {
		$jscode = input('param.code');
		$userinfo = input('param.userinfo');
		$fromid = input('param.pid');
		$wxapp = \app\common\System::appinfo(aid, 'wx');
		if ($wxapp['authtype'] == 1) {
			$url = 'https://api.weixin.qq.com/sns/component/jscode2session?appid=' . $wxapp['appid'] . '&component_appid=' . \app\common\Wechat::component_appid() . '&js_code=' . $jscode . '&grant_type=authorization_code&component_access_token=' . \app\common\Wechat::component_access_token();
		} else {
			$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $wxapp['appid'] . '&secret=' . $wxapp['appsecret'] . '&js_code=' . $jscode . '&grant_type=authorization_code';
		}
		$rs = request_get($url);
		$rs = json_decode($rs, true);
		if ($rs['errcode'] > 0) {
			return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($rs)]);
		}
		$openid = $rs['openid'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$unionid = $rs['unionid'];
		$session_key = $rs['session_key'];
		$member = Db::name('member')->where('aid', aid)->where(platform . 'openid', $openid)->find();
		if (!$member && $unionid) {
			$member = Db::name('member')->where('aid', aid)->where('unionid', $unionid)->find();
			if ($member) {
				Db::name('member')->where('id', $member['id'])->update([platform . 'openid' => $openid]);
			}

		}
		if (!$member) {
			$rs['userinfo'] = $userinfo;
			cache($this->sessionid . '_' . platform . 'UserInfo', $rs, 3600);

			if ($this->sysset['login_setnickname'] && (!$userinfo['nickName'] || $userinfo['nickName'] == '微信用户')) {
				return $this->json(['status' => 3, 'msg' => '设置头像昵称', 'login_setnickname' => $this->sysset['login_setnickname'], 'login_bind' => $this->sysset['login_bind']]);
			}
			if ($this->sysset['login_bind']) {
				return $this->json(['status' => 2, 'msg' => '绑定手机号', 'login_bind' => $this->sysset['login_bind']]);
			}
			return $this->wxRegister();
		} else {
			$mid = $member['id'];

			if (!$member['headimg'] || strpos($member['headimg'], '/static/img/touxiang.png') !== false) {
				$update = [];
				$update['headimg'] = \app\common\Pic::uploadoss($userinfo['avatarUrl']);
				$update['nickname'] = $userinfo['nickName'];
				$update['sex'] = $userinfo['gender'];
				$update['province'] = $userinfo['province'];
				$update['city'] = $userinfo['city'];
				Db::name('member')->where('id', $member['id'])->update($update);
			}
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			//更新session信息
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}

	public function wxRegister() {
		$rs = cache($this->sessionid . '_' . platform . 'UserInfo');
		$userinfo = $rs['userinfo'];
		$fromid = input('param.pid');
		if ($rs['errcode'] > 0) {
			return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($rs)]);
		}
		$openid = $rs['openid'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$unionid = $rs['unionid'];
		$session_key = $rs['session_key'];
		$member = Db::name('member')->where('aid', aid)->where(platform . 'openid', $openid)->find();

		if (!$member && $unionid) {
			$member = Db::name('member')->where('aid', aid)->where('unionid', $unionid)->find();
			if ($member) {
				Db::name('member')->where('id', $member['id'])->update([platform . 'openid' => $openid]);
			}

		}
		if (input('param.code') && input('post.iv') && input('post.encryptedData')) {
			$jscode = input('param.code');
			$encryptedData = input('post.encryptedData');
			$iv = input('post.iv');

			$wxapp = \app\common\System::appinfo(aid, 'wx');
			if ($wxapp['authtype'] == 1) {
				$url = 'https://api.weixin.qq.com/sns/component/jscode2session?appid=' . $wxapp['appid'] . '&component_appid=' . \app\common\Wechat::component_appid() . '&js_code=' . $jscode . '&grant_type=authorization_code&component_access_token=' . \app\common\Wechat::component_access_token();
			} else {
				$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $wxapp['appid'] . '&secret=' . $wxapp['appsecret'] . '&js_code=' . $jscode . '&grant_type=authorization_code';
			}
			$rs = request_get($url);
			$rs = json_decode($rs, true);
			if ($rs['errcode'] > 0) {
				return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($rs)]);
			}
			$session_key = $rs['session_key'];
			if (!$session_key) {
				return json(['status' => 0, 'msg' => '获取授权信息失败']);
			}

			$pc = new \app\common\WxBizDataCrypt($wxapp['appid'], $session_key);
			$errCode = $pc->decryptData($encryptedData, $iv, $rdata);
			$rdata = json_decode($rdata, true);

			if ($rdata['phoneNumber']) {
				$tel = $rdata['phoneNumber'];
			} else {
				return json(['status' => 0, 'msg' => '授权获取手机号失败']);
			}
		} elseif (input('param.tel')) {
			$tel = input('param.tel');
			$smscode = input('param.smscode');
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
		}
		if ($tel) {
			if ($member) {
				$hasmember = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if (!$hasmember) {
					Db::name('member')->where('id', $member['id'])->update(['tel' => $tel]);
				} else {
					return $this->json(['status' => 0, 'msg' => '该手机号已被其他用户绑定']);
				}
			} else {
				$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if ($member) {
					$update = [];
					$update[platform . 'openid'] = $openid;
					$update['session_key'] = $session_key;
					if ($unionid) {
						$update['unionid'] = $unionid;
					}
					if (!$member['headimg'] || strpos($member['headimg'], '/static/img/touxiang.png') !== false) {
						$update['headimg'] = \app\common\Pic::uploadoss($userinfo['avatarUrl']);
						$update['nickname'] = $userinfo['nickName'];
						$update['sex'] = $userinfo['gender'];
						$update['province'] = $userinfo['province'];
						$update['city'] = $userinfo['city'];
					}
					Db::name('member')->where('id', $member['id'])->update($update);
				}
			}
		}
		$tmplids = [];
		if (!$member) {
			$data = [];
			$data['aid'] = aid;
			$data[platform . 'openid'] = $openid;
			$data['session_key'] = $session_key;
			if ($unionid) {
				$data['unionid'] = $unionid;
			}
			if (input('param.headimg')) {
				$data['headimg'] = input('param.headimg');
			} else {
				$data['headimg'] = \app\common\Pic::uploadoss($userinfo['avatarUrl']);
			}
			if (input('param.nickname')) {
				$data['nickname'] = input('param.nickname');
			} else {
				$data['nickname'] = $userinfo['nickName'];
			}
			$data['sex'] = $userinfo['gender'];
			$data['province'] = $userinfo['province'];
			$data['city'] = $userinfo['city'];
//            $data['session_id'] = $this->sessionid;
			$data['createtime'] = time();
			$data['last_visittime'] = time();
			if ($tel) {
				$data['tel'] = $tel;
			}
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));

			if (platform == 'wx' && $this->sysset['reg_check'] == 1) {
				$wx_tmplset = Db::name('wx_tmplset')->where('aid', aid)->find();
				if ($wx_tmplset['tmpl_shenhe_new']) {
					$tmplids[] = $wx_tmplset['tmpl_shenhe_new'];
				}
			}
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid, 'tmplids' => $tmplids]);
	}

	//授权微信短信
	public function authphone() {
		if (!in_array(platform, ['wx', 'mp'])) {
			return $this->json(['status' => 0, '不支持手机号授权']);
		}
		if (input('param.code') && input('post.iv') && input('post.encryptedData')) {
			$jscode = input('param.code');
			$encryptedData = input('post.encryptedData');
			$iv = input('post.iv');
			$wxapp = \app\common\System::appinfo(aid, 'wx');
			if ($wxapp['authtype'] == 1) {
				$url = 'https://api.weixin.qq.com/sns/component/jscode2session?appid=' . $wxapp['appid'] . '&component_appid=' . \app\common\Wechat::component_appid() . '&js_code=' . $jscode . '&grant_type=authorization_code&component_access_token=' . \app\common\Wechat::component_access_token();
			} else {
				$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $wxapp['appid'] . '&secret=' . $wxapp['appsecret'] . '&js_code=' . $jscode . '&grant_type=authorization_code';
			}
			$rs = request_get($url);
			$rs = json_decode($rs, true);
			if ($rs['errcode'] > 0) {
				return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($rs)]);
			}
			$session_key = $rs['session_key'];
			if (!$session_key) {
				return json(['status' => 0, 'msg' => '获取授权信息失败']);
			}

			$pc = new \app\common\WxBizDataCrypt($wxapp['appid'], $session_key);
			$errCode = $pc->decryptData($encryptedData, $iv, $rdata);
			$rdata = json_decode($rdata, true);
			if ($rdata['phoneNumber']) {
				$tel = $rdata['phoneNumber'];
				return json(['status' => 1, 'tel' => $tel]);
			} else {
				return json(['status' => 0, 'msg' => '授权获取手机号失败']);
			}
		} else {
			return json(['status' => 0, 'msg' => '参数错误']);
		}
	}

	//app微信登录
	public function appwxlogin() {
		$jscode = input('param.code');
		$fromid = input('param.pid');
		$app = \app\common\System::appinfo(aid, 'app');

		$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $app['appid'] . '&secret=' . $app['appsecret'] . '&code=' . $jscode . '&grant_type=authorization_code';
		$rs = request_get($url);
		$rs = json_decode($rs, true);
		if ($rs['errcode'] > 0) {
			return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($rs)]);
		}
		$openid = $rs['openid'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$unionid = $rs['unionid'];
		$access_token = $rs['access_token'];

		$member = Db::name('member')->where('aid', aid)->where('appopenid', $openid)->find();
		if (!$member && $unionid) {
			$member = Db::name('member')->where('aid', aid)->where('unionid', $unionid)->find();
			if ($member) {
				Db::name('member')->where('id', $member['id'])->update(['appopenid' => $openid]);
			}

		}
		if (!$member) {
			$url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
			$result = request_get($url);
			$result = json_decode($result, true);
			if ($result['errcode'] > 0) {
				return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($result)]);
			}

			cache($this->sessionid . '_' . platform . 'UserInfo', $result, 3600);
			$info = Db::name('admin_set')->where('aid', aid)->find();
			if ($info['login_bind']) {
				return $this->json(['status' => 2, 'msg' => '绑定手机号', 'login_bind' => $info['login_bind']]);
			}
			return $this->appwxRegister();
		} else {
			$mid = $member['id'];

			if (!$member['headimg'] || strpos($member['headimg'], '/static/img/touxiang.png') !== false) {
				$update = [];
				$update['headimg'] = \app\common\Pic::uploadoss($result['headimgurl']);
				$update['nickname'] = $result['nickname'];
				$update['sex'] = $result['sex'];
				$update['province'] = $result['province'];
				$update['city'] = $result['city'];
				Db::name('member')->where('id', $member['id'])->update($update);
			}

//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//app微信注册
	public function appwxRegister() {
		$fromid = input('param.pid');
		$tel = input('param.tel');
		$smscode = input('param.smscode');
		$result = cache($this->sessionid . '_' . platform . 'UserInfo');
		$openid = $result['openid'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$unionid = $result['unionid'];
		$access_token = $result['access_token'];

		$member = Db::name('member')->where('aid', aid)->where('appopenid', $openid)->find();
		if (!$member && $unionid) {
			$member = Db::name('member')->where('aid', aid)->where('unionid', $unionid)->find();
			if ($member) {
				Db::name('member')->where('id', $member['id'])->update(['appopenid' => $openid]);
			}

		}
		if ($tel) {
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			if ($member) {
				$hasmember = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if (!$hasmember) {
					Db::name('member')->where('id', $member['id'])->update(['tel' => $tel]);
				} else {
					return $this->json(['status' => 0, 'msg' => '该手机号已被其他用户绑定']);
				}
			} else {
				$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if ($member) {
					$update = [];
					$update['appopenid'] = $openid;
					if ($unionid) {
						$update['unionid'] = $unionid;
					}
					if (!$member['headimg'] || strpos($member['headimg'], '/static/img/touxiang.png') !== false) {
						$update['headimg'] = \app\common\Pic::uploadoss($result['headimgurl']);
						$update['nickname'] = $result['nickname'];
						$update['sex'] = $result['sex'];
						$update['province'] = $result['province'];
						$update['city'] = $result['city'];
					}
					Db::name('member')->where('id', $member['id'])->update($update);
				}
			}
		}
		if (!$member) {
			if ($result['errcode'] > 0) {
				return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($result)]);
			}
			$data = [];
			$data['aid'] = aid;
			$data['appopenid'] = $openid;
			if ($unionid) {
				$data['unionid'] = $unionid;
			}
			$data['nickname'] = $result['nickname'];
			$data['sex'] = $result['sex'];
			$data['province'] = $result['province'];
			$data['city'] = $result['city'];
			$data['country'] = $result['country'];
			$data['headimg'] = \app\common\Pic::uploadoss($result['headimgurl']);

//            $data['session_id'] = $this->sessionid;
			$data['createtime'] = time();
			$data['last_visittime'] = time();
			if ($tel) {
				$data['tel'] = $tel;
			}
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//百度小程序授权登录
	public function baidulogin() {
		$jscode = input('param.code');
		$fromid = input('param.pid');
		$baiduapp = \app\common\System::appinfo(aid, 'baidu');
		$rs = request_post('https://spapi.baidu.com/oauth/jscode2sessionkey', ['code' => $jscode, 'client_id' => $baiduapp['appkey'], 'sk' => $baiduapp['appsecret']]);
		$rs = json_decode($rs, true);
		if ($rs['errno'] > 0) {
			return $this->json(['status' => 0, 'msg' => $rs['error_description']]);
		}
		$openid = $rs['openid'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$member = Db::name('member')->where('aid', aid)->where('baiduopenid', $openid)->find();
		if (!$member) {
			cache($this->sessionid . '_' . platform . 'UserInfo', $rs, 3600);
			if ($this->sysset['login_setnickname'] && (!$userinfo['nickName'] || $userinfo['nickName'] == '微信用户')) {
				return $this->json(['status' => 3, 'msg' => '设置头像昵称', 'login_setnickname' => $this->sysset['login_setnickname'], 'login_bind' => $this->sysset['login_bind']]);
			}
			if ($this->sysset['login_bind']) {
				return $this->json(['status' => 2, 'msg' => '绑定手机号', 'login_bind' => $this->sysset['login_bind']]);
			}
			return $this->baiduRegister();
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//百度小程序授权注册
	public function baiduRegister() {
		$fromid = input('param.pid');
		$tel = input('param.tel');
		$smscode = input('param.smscode');
		$rs = cache($this->sessionid . '_' . platform . 'UserInfo');
		$openid = $rs['openid'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$member = Db::name('member')->where('aid', aid)->where('baiduopenid', $openid)->find();
		if ($tel) {
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			if ($member) {
				$hasmember = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if (!$hasmember) {
					Db::name('member')->where('id', $member['id'])->update(['tel' => $tel]);
				} else {
					return $this->json(['status' => 0, 'msg' => '该手机号已被其他用户绑定']);
				}
			} else {
				$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if ($member) {
					$update = [];
					$update['baiduopenid'] = $openid;
					Db::name('member')->where('id', $member['id'])->update($update);
				}
			}
		}
		if (!$member) {
			$data = [];
			$data['aid'] = aid;
			$data['baiduopenid'] = $openid;
			$data['sex'] = 3;
			if (input('param.headimg')) {
				$data['headimg'] = input('param.headimg');
			} else {
				$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
			}
			if (input('param.nickname')) {
				$data['nickname'] = input('param.nickname');
			} else {
				$data['nickname'] = '百度用户' . random(6);
			}

			$data['createtime'] = time();
//            $data['session_id'] = $this->sessionid;
			$data['last_visittime'] = time();
			if ($tel) {
				$data['tel'] = $tel;
			}
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//QQ小程序授权登录
	public function qqlogin() {
		$jscode = input('param.code');
		$fromid = input('param.pid');
		$qqapp = \app\common\System::appinfo(aid, 'qq');
		$rs = request_get('https://api.q.qq.com/sns/jscode2session?appid=' . $qqapp['appid'] . '&secret=' . $qqapp['appsecret'] . '&js_code=' . $jscode . '&grant_type=authorization_code');
		$rs = json_decode($rs, true);
		$openid = $rs['openid'];
		if ($rs['errcode'] > 0 || !$openid) {
			return $this->json(['status' => 0, 'msg' => $rs['errmsg']]);
		}
		$member = Db::name('member')->where('aid', aid)->where('qqopenid', $openid)->find();
		if (!$member) {
			cache($this->sessionid . '_' . platform . 'UserInfo', $rs, 3600);
			if ($this->sysset['login_setnickname'] && (!$userinfo['nickName'] || $userinfo['nickName'] == '微信用户')) {
				return $this->json(['status' => 3, 'msg' => '设置头像昵称', 'login_setnickname' => $this->sysset['login_setnickname'], 'login_bind' => $this->sysset['login_bind']]);
			}
			if ($this->sysset['login_bind']) {
				return $this->json(['status' => 2, 'msg' => '绑定手机号', 'login_bind' => $this->sysset['login_bind']]);
			}
			return $this->qqRegister();
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//QQ小程序授权注册
	public function qqRegister() {
		$fromid = input('param.pid');
		$tel = input('param.tel');
		$smscode = input('param.smscode');
		$rs = cache($this->sessionid . '_' . platform . 'UserInfo');
		$openid = $rs['openid'];
		if ($rs['errcode'] > 0 || !$openid) {
			return $this->json(['status' => 0, 'msg' => $rs['errmsg']]);
		}
		$member = Db::name('member')->where('aid', aid)->where('qqopenid', $openid)->find();
		if ($tel) {
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			if ($member) {
				$hasmember = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if (!$hasmember) {
					Db::name('member')->where('id', $member['id'])->update(['tel' => $tel]);
				} else {
					return $this->json(['status' => 0, 'msg' => '该手机号已被其他用户绑定']);
				}
			} else {
				$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if ($member) {
					$update = [];
					$update['qqopenid'] = $openid;
					Db::name('member')->where('id', $member['id'])->update($update);
				}
			}
		}
		if (!$member) {
			$data = [];
			$data['aid'] = aid;
			$data['qqopenid'] = $openid;
			$data['sex'] = 3;
			if (input('param.headimg')) {
				$data['headimg'] = input('param.headimg');
			} else {
				$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
			}
			if (input('param.nickname')) {
				$data['nickname'] = input('param.nickname');
			} else {
				$data['nickname'] = 'QQ用户' . random(6);
			}

			$data['createtime'] = time();
//            $data['session_id'] = $this->sessionid;
			$data['last_visittime'] = time();
			if ($tel) {
				$data['tel'] = $tel;
			}
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//头条小程序授权登录
	public function toutiaologin() {
		$jscode = input('param.code');
		$fromid = input('param.pid');
		$qqapp = \app\common\System::appinfo(aid, 'toutiao');
		$rs = request_get('https://developer.toutiao.com/api/apps/jscode2session?appid=' . $qqapp['appid'] . '&secret=' . $qqapp['appsecret'] . '&code=' . $jscode);
		$rs = json_decode($rs, true);
		if (!$rs['openid']) {
			return $this->json(['status' => 0, 'msg' => $rs['errmsg']]);
		}
		$openid = $rs['openid'];
		$member = Db::name('member')->where('aid', aid)->where('toutiaoopenid', $openid)->find();
		if (!$member) {
			cache($this->sessionid . '_' . platform . 'UserInfo', $rs, 3600);
			if ($this->sysset['login_setnickname'] && (!$userinfo['nickName'] || $userinfo['nickName'] == '微信用户')) {
				return $this->json(['status' => 3, 'msg' => '设置头像昵称', 'login_setnickname' => $this->sysset['login_setnickname'], 'login_bind' => $this->sysset['login_bind']]);
			}
			if ($this->sysset['login_bind']) {
				return $this->json(['status' => 2, 'msg' => '绑定手机号', 'login_bind' => $this->sysset['login_bind']]);
			}
			return $this->toutiaoRegister();
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//头条小程序授权注册
	public function toutiaoRegister() {
		$fromid = input('param.pid');
		$tel = input('param.tel');
		$smscode = input('param.smscode');
		$rs = cache($this->sessionid . '_' . platform . 'UserInfo');
		if (!$rs['openid']) {
			return $this->json(['status' => 0, 'msg' => $rs['errmsg']]);
		}
		$openid = $rs['openid'];
		$member = Db::name('member')->where('aid', aid)->where('toutiaoopenid', $openid)->find();
		if ($tel) {
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			if ($member) {
				$hasmember = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if (!$hasmember) {
					Db::name('member')->where('id', $member['id'])->update(['tel' => $tel]);
				} else {
					return $this->json(['status' => 0, 'msg' => '该手机号已被其他用户绑定']);
				}
			} else {
				$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if ($member) {
					$update = [];
					$update['toutiaoopenid'] = $openid;
					Db::name('member')->where('id', $member['id'])->update($update);
				}
			}
		}
		if (!$member) {
			$data = [];
			$data['aid'] = aid;
			$data['toutiaoopenid'] = $openid;
			$data['sex'] = 3;

			if (input('param.headimg')) {
				$data['headimg'] = input('param.headimg');
			} else {
				$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
			}
			if (input('param.nickname')) {
				$data['nickname'] = input('param.nickname');
			} else {
				$data['nickname'] = '用户' . random(6);
			}

			$data['createtime'] = time();
//            $data['session_id'] = $this->sessionid;
			$data['last_visittime'] = time();
			if ($tel) {
				$data['tel'] = $tel;
			}
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//支付宝小程序授权登录
	public function alipaylogin() {
		$fromid = input('param.pid');

		$jscode = input('post.code');
		if (strpos($jscode, '&app_id=') > 0) {
			$jscode = explode('&app_id=', $jscode)[0];
		}

		$alipayapp = \app\common\System::appinfo(aid, 'alipay');

		require_once ROOT_PATH . '/extend/aop/AopClient.php';
		require_once ROOT_PATH . '/extend/aop/request/AlipaySystemOauthTokenRequest.php';

		$aop = new \AopClient();
		$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
		$aop->appId = $alipayapp['appid'];
		$aop->rsaPrivateKey = $alipayapp['appsecret'];
		$aop->alipayrsaPublicKey = $alipayapp['publickey'];
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset = 'utf-8';
		$aop->format = 'json';
		$request = new \AlipaySystemOauthTokenRequest();
		$request->setGrantType("authorization_code");
		$request->setCode($jscode);
		$result = $aop->execute($request);
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$resultCode = $result->$responseNode->code;
		if (!empty($resultCode) && $resultCode != 10000) {
			return json(['status' => 0, 'msg' => $result->$responseNode->sub_msg]);
		}

		$openid = $result->$responseNode->user_id;
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败', '$result' => $result]);
		}

		$member = Db::name('member')->where('aid', aid)->where('alipayopenid', $openid)->find();
		if (!$member) {
			cache($this->sessionid . '_' . platform . 'UserInfo', ['openid' => $openid, 'resultCode' => $resultCode, 'msg' => $result->$responseNode->sub_msg], 3600);
			if ($this->sysset['login_setnickname'] && (!$userinfo['nickName'] || $userinfo['nickName'] == '微信用户')) {
				return $this->json(['status' => 3, 'msg' => '设置头像昵称', 'login_setnickname' => $this->sysset['login_setnickname'], 'login_bind' => $this->sysset['login_bind']]);
			}
			if ($this->sysset['login_bind']) {
				return $this->json(['status' => 2, 'msg' => '绑定手机号', 'login_bind' => $this->sysset['login_bind']]);
			}
			return $this->alipayRegister();
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//支付宝小程序授权注册
	public function alipayRegister() {
		$fromid = input('param.pid');
		$tel = input('param.tel');
		$smscode = input('param.smscode');

		$rs = cache($this->sessionid . '_' . platform . 'UserInfo');
		if (!empty($rs['resultCode']) && $rs['resultCode'] != 10000) {
			return json(['status' => 0, 'msg' => $rs['msg']]);
		}

		$openid = $rs['openid'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$member = Db::name('member')->where('aid', aid)->where('alipayopenid', $openid)->find();
		if ($tel) {
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			if ($member) {
				$hasmember = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if (!$hasmember) {
					Db::name('member')->where('id', $member['id'])->update(['tel' => $tel]);
				} else {
					return $this->json(['status' => 0, 'msg' => '该手机号已被其他用户绑定']);
				}
			} else {
				$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if ($member) {
					$update = [];
					$update['alipayopenid'] = $openid;
					Db::name('member')->where('id', $member['id'])->update($update);
				}
			}
		}
		if (!$member) {
			$data = [];
			$data['aid'] = aid;
			$data['alipayopenid'] = $openid;
			$data['sex'] = 3;

			if (input('param.headimg')) {
				$data['headimg'] = input('param.headimg');
			} else {
				$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
			}
			if (input('param.nickname')) {
				$data['nickname'] = input('param.nickname');
			} else {
				$data['nickname'] = '用户' . random(6);
			}

			$data['createtime'] = time();
//            $data['session_id'] = $this->sessionid;
			$data['last_visittime'] = time();
			if ($tel) {
				$data['tel'] = $tel;
			}
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//Apple授权登录
	public function ioslogin() {
		$fromid = input('param.pid');
		$userinfo = input('param.userInfo');
		if (!$userinfo || !$userinfo['openId']) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$openid = $userinfo['openId'];
		$member = Db::name('member')->where('aid', aid)->where('iosopenid', $openid)->find();
		if (!$member) {
			cache($this->sessionid . '_' . platform . 'UserInfo', $userinfo, 3600);
			$info = Db::name('admin_set')->where('aid', aid)->find();
			if ($info['login_bind']) {
				return $this->json(['status' => 2, 'msg' => '绑定手机号', 'login_bind' => $info['login_bind']]);
			}
			return $this->iosRegister();
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//Apple授权注册
	public function iosRegister() {
		$fromid = input('param.pid');
		$tel = input('param.tel');
		$smscode = input('param.smscode');
		$userinfo = cache($this->sessionid . '_' . platform . 'UserInfo');
		$openid = $userinfo['openId'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败', '$userinfo' => $userinfo]);
		}

		$member = Db::name('member')->where('aid', aid)->where('iosopenid', $openid)->find();
		if ($tel) {
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			if ($member) {
				$hasmember = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if (!$hasmember) {
					Db::name('member')->where('id', $member['id'])->update(['tel' => $tel]);
				} else {
					return $this->json(['status' => 0, 'msg' => '该手机号已被其他用户绑定']);
				}
			} else {
				$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if ($member) {
					$update = [];
					$update['iosopenid'] = $openid;
					Db::name('member')->where('id', $member['id'])->update($update);
				}
			}
		}
		if (!$member) {
			$data = [];
			$data['aid'] = aid;
			$data['iosopenid'] = $openid;
			$data['sex'] = 3;
			$data['nickname'] = $userinfo['fullName']['givenName'];
			$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
			$data['createtime'] = time();
//            $data['session_id'] = $this->sessionid;
			$data['last_visittime'] = time();
			if ($tel) {
				$data['tel'] = $tel;
			}
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
		} else {
			$mid = $member['id'];
//			if($member['session_id']){
			//				$this->sessionid = $member['session_id'];
			//			}else{
			//				Db::name('member')->where('id',$mid)->update(['session_id'=>$this->sessionid]);
			//			}
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}

	//Google授权登录
	public function googlelogin() {
		$fromid = input('param.pid');
		//if(getcustom('test')){
		//\think\facade\Log::write(input('param.res'));
		//}
		$userinfo = input('param.userInfo');
		if (!$userinfo || !$userinfo['openId']) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$openid = $userinfo['openId'];
		$member = Db::name('member')->where('aid', aid)->where('googleopenid', $openid)->find();
		if (!$member) {
			cache($this->sessionid . '_' . platform . 'UserInfo', $userinfo, 3600);
			$info = Db::name('admin_set')->where('aid', aid)->find();
			if ($info['login_bind']) {
				return $this->json(['status' => 2, 'msg' => '绑定手机号', 'login_bind' => $info['login_bind']]);
			}
			return $this->googleRegister();
		} else {
			$mid = $member['id'];
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}
	//Google授权注册
	public function googleRegister() {
		$fromid = input('param.pid');
		$tel = input('param.tel');
		$smscode = input('param.smscode');
		$userinfo = cache($this->sessionid . '_' . platform . 'UserInfo');
		$openid = $userinfo['openId'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败', '$userinfo' => $userinfo]);
		}

		$member = Db::name('member')->where('aid', aid)->where('googleopenid', $openid)->find();
		if ($tel) {
			if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
				cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
				return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
			}
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			if ($member) {
				$hasmember = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if (!$hasmember) {
					Db::name('member')->where('id', $member['id'])->update(['tel' => $tel]);
				} else {
					return $this->json(['status' => 0, 'msg' => '该手机号已被其他用户绑定']);
				}
			} else {
				$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
				if ($member) {
					$update = [];
					$update['googleopenid'] = $openid;
					Db::name('member')->where('id', $member['id'])->update($update);
				}
			}
		}
		if (!$member) {
			$data = [];
			$data['aid'] = aid;
			$data['googleopenid'] = $openid;
			$data['sex'] = 3;
			$data['nickname'] = $userinfo['name'] ?? $userinfo['email'];
			$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
			$data['createtime'] = time();
			$data['last_visittime'] = time();
			if ($tel) {
				$data['tel'] = $tel;
			}
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
		} else {
			$mid = $member['id'];
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);
	}

	//注册
	public function reg() {
		$sysset = Db::name('admin_set')->where('aid', aid)->find();
		$platform = platform;
		$logintype = $sysset['logintype_' . $platform];
		$logintype = explode(',', $logintype);
		if (!in_array('1', $logintype)) {
			return $this->json(['status' => 0, 'msg' => '自主注册未开启']);
		}

		$xieyi = Db::name('admin_set_xieyi')->where('aid', aid)->find();
		if (!$xieyi) {
			$xieyi = ['status' => 0, 'content' => ''];
		}

		$pid = input('param.pid');
		if ($pid) {
			$parent = Db::name('member')->where('aid', aid)->where('id', $pid)->field('id,nickname,headimg,yqcode')->find();
		}

		$smsset = Db::name('admin_set_sms')->where('aid', aid)->find();
		if ($smsset && $smsset['status'] == 1 && $smsset['tmpl_smscode'] && $smsset['tmpl_smscode_st'] == 1) {
			$needsms = true;
		} else {
			$needsms = false;
		}

		if ($sysset['reg_invite_code_type'] == 1) {
			$reg_invite_code_text = '邀请码';
		} else {
			$reg_invite_code_text = '手机号';
		}
		//定制内容.77
		$formField = [];
		$hasCustom = 0;
		if (getcustom('register_fields')) {
			if (in_array('1', $logintype)) {
				$formField = Db::name('register_form')->where('aid', aid)->find();
				if ($formField && $formField['content']) {
					$formField['content'] = json_decode($formField['content'], true);
					$hasCustom = 1;
				} else {
					$formField = [];
				}
			}
		}

		$rdata = [];
		$rdata['status'] = 1;
		$rdata['logintype_1'] = in_array('1', $logintype); //注册登录
		$rdata['logintype_2'] = in_array('2', $logintype); //手机验证码登录
		$rdata['logintype_3'] = platform != 'h5' ? in_array('3', $logintype) : false; //授权登录 h5时去掉授权登录
		$rdata['name'] = $sysset['name'];
		$rdata['logo'] = $sysset['logo'];
		$rdata['reg_invite_code'] = $sysset['reg_invite_code'];
		$rdata['reg_invite_code_text'] = $reg_invite_code_text;
		$rdata['reg_invite_code_type'] = $sysset['reg_invite_code_type'];
		$rdata['xystatus'] = $xieyi['status'];
		$rdata['xyname'] = $xieyi['name'];
		$rdata['xycontent'] = $xieyi['content'];
		$rdata['xyname2'] = $xieyi['name2'];
		$rdata['xycontent2'] = $xieyi['content2'];
		$rdata['needsms'] = $needsms;
		$rdata['parent'] = $parent ? $parent : null;
		$rdata['platform'] = platform;
		$rdata['has_custom'] = $hasCustom;
		$rdata['custom_form_field'] = $formField;
		return $this->json($rdata);
	}
	public function regsub() {
		$tel = input('param.tel');
		$pwd = input('param.pwd');
		$smscode = input('param.smscode');
		$fromid = input('param.pid');
		$yqcode = input('param.yqcode');

		if (!preg_match("/^1[3456789]\d{9}$/", $tel)) {
			return $this->json(['status' => 0, 'msg' => '手机号格式错误']);
		}

		$smsset = Db::name('admin_set_sms')->where('aid', aid)->find();
		if ($smsset && $smsset['status'] == 1 && $smsset['tmpl_smscode'] && $smsset['tmpl_smscode_st'] == 1) {
			$needsms = true;
		} else {
			$needsms = false;
		}
		if ($needsms && md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
			cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
			return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
		}
		$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
		if ($member) {
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			return $this->json(['status' => 0, 'msg' => '该手机号已注册，请直接登录']);
		} else {
			$data = [];
			$data['aid'] = aid;
			$data['tel'] = $tel;
			$data['pwd'] = md5($pwd);
			$data['nickname'] = substr($tel, 0, 3) . '****' . substr($tel, -4);
			$data['sex'] = 3;
			$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
			$data['createtime'] = time();
			$data['last_visittime'] = time();
//			$data['session_id'] = $this->sessionid;
			$sysset = Db::name('admin_set')->where('aid', aid)->find();
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			} elseif ($yqcode) {
				if ($sysset['reg_invite_code']) {
					if ($sysset['reg_invite_code_type'] == 1) {
//邀请码
						$upuser = Db::name('member')->where('aid', aid)->where('yqcode', $yqcode)->find();
						if (!$upuser) {
							return $this->json(['status' => 0, 'msg' => '邀请码不正确']);
						}

					} elseif ($sysset['reg_invite_code_type'] == 2) {
//id
						$upuser = Db::name('member')->where('aid', aid)->where('id', intval($fromid))->find();
						if (!$upuser) {
							return $this->json(['status' => 0, 'msg' => '邀请码不正确']);
						}

					} else {
//手机号
						$upuser = Db::name('member')->where('aid', aid)->where('tel', $yqcode)->find();
						if (!$upuser) {
							return $this->json(['status' => 0, 'msg' => '邀请人手机号不正确']);
						}

					}

					$uplv = Db::name('member_level')->where('aid', aid)->where('id', $upuser['levelid'])->find();
					if ($upuser && $uplv['can_agent'] != 0) {
						$data['pid'] = $upuser['id'];
					}
				}
			}
			if ($sysset['reg_invite_code'] == 2 && !$upuser) {
				//必须邀请注册
				return $this->json(['status' => 0, 'msg' => '必须有邀请人邀请注册']);
			}
			//自定义表单start
			if (getcustom('register_fields')) {
				$res = $this->customRegister(input('param.customformdata'), input('param.customformid'));
				if ($res['status'] != 1) {
					return $this->json(['status' => 0, 'msg' => $res['msg']]);
				} else if ($res['status'] == 1 && isset($res['recordid']) && $res['recordid'] > 0) {
					$data['form_record_id'] = $res['recordid'];
				}
			}
			//自定义表单end
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
			cache($this->sessionid . '_mid', $mid, 7 * 86400);
			cache($this->sessionid . '_smscode', null);
			cache($this->sessionid . '_smscodetimes', null);
			$tmplids = [];
			if (platform == 'wx' && $this->sysset['reg_check'] == 1) {
				$wx_tmplset = Db::name('wx_tmplset')->where('aid', aid)->find();
				if ($wx_tmplset['tmpl_shenhe_new']) {
					$tmplids[] = $wx_tmplset['tmpl_shenhe_new'];
				}
			}
			return $this->json(['status' => 1, 'msg' => '注册成功', 'mid' => $mid, 'toappurl' => $this->sysset['appurl'], 'tmplids' => $tmplids]);
		}
	}
	//找回密码
	public function getpwd() {
		$tel = input('param.tel');
		$pwd = input('param.pwd');
		$smscode = input('param.smscode');
		if (md5($tel . '-' . $smscode) != cache($this->sessionid . '_smscode') || cache($this->sessionid . '_smscodetimes') > 5) {
			cache($this->sessionid . '_smscodetimes', cache($this->sessionid . '_smscodetimes') + 1);
			return $this->json(['status' => 0, 'msg' => '短信验证码错误']);
		}
		cache($this->sessionid . '_smscode', null);
		cache($this->sessionid . '_smscodetimes', null);
		$member = Db::name('member')->where('aid', aid)->where('tel', $tel)->find();
		if (!$member) {
			return $this->json(['status' => 0, 'msg' => '该手机号未注册']);
		}

		Db::name('member')->where('aid', aid)->where('id', $member['id'])->update(['pwd' => md5($pwd)]);
		return $this->json(['status' => 1, 'msg' => '重置成功', 'mid' => $member['id']]);
	}
	//设置微信小程序openid
	public function setwxopenid() {
		if (!$this->member) {
			return json(['status' => 0, 'msg' => '未登陆']);
		}

		$post = input('post.');
		$set = Db::name('admin_set')->where('aid', aid)->find();
		$jscode = input('post.code');
		$wxapp = \app\common\System::appinfo(aid, 'wx');
		if ($wxapp['authtype'] == 1) {
			$url = 'https://api.weixin.qq.com/sns/component/jscode2session?appid=' . $wxapp['appid'] . '&component_appid=' . \app\common\Wechat::component_appid() . '&js_code=' . $jscode . '&grant_type=authorization_code&component_access_token=' . \app\common\Wechat::component_access_token();
		} else {
			$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $wxapp['appid'] . '&secret=' . $wxapp['appsecret'] . '&js_code=' . $jscode . '&grant_type=authorization_code';
		}
		$rs = request_get($url);
		$rs = json_decode($rs, true);
		if ($rs['errcode'] > 0) {
			return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($rs)]);
		}
		$openid = $rs['openid'];
		$unionid = $rs['unionid'];
		if ($openid) {
			$updata = [];
			$updata['wxopenid'] = $openid;
			if ($unionid) {
				$updata['unionid'] = $unionid;
			}
			Db::name('member')->where('id', mid)->update($updata);
		}
		return json(['status' => 1, 'msg' => '更新成功']);
	}
	//设置支付宝小程序openid
	public function setalipayopenid() {
		if (!$this->member) {
			return json(['status' => 0, 'msg' => '未登陆']);
		}

		$post = input('post.');
		$set = Db::name('admin_set')->where('aid', aid)->find();
		$jscode = input('post.code');
		$alipayapp = \app\common\System::appinfo(aid, 'alipay');

		require_once ROOT_PATH . '/extend/aop/AopClient.php';
		require_once ROOT_PATH . '/extend/aop/request/AlipaySystemOauthTokenRequest.php';

		$aop = new \AopClient();
		$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
		$aop->appId = $alipayapp['appid'];
		$aop->rsaPrivateKey = $alipayapp['appsecret'];
		$aop->alipayrsaPublicKey = $alipayapp['publickey'];
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset = 'utf-8';
		$aop->format = 'json';
		$request = new \AlipaySystemOauthTokenRequest();
		$request->setGrantType("authorization_code");
		$request->setCode($jscode);
		$result = $aop->execute($request);
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$resultCode = $result->$responseNode->code;
		if (!empty($resultCode) && $resultCode != 10000) {
			return json(['status' => 0, 'msg' => $result->$responseNode->sub_msg]);
		} else {
			$openid = $result->$responseNode->user_id;
			if (!$openid) {
				return json(['status' => 0, 'msg' => '获取授权信息失败']);
			}

			$updata = [];
			$updata['alipayopenid'] = $openid;
			Db::name('member')->where('id', mid)->update($updata);
			return json(['status' => 1, 'msg' => '更新成功']);
		}
	}
	//设置百度小程序openid
	public function setbaiduopenid() {
		if (!$this->member) {
			return json(['status' => 0, 'msg' => '未登陆']);
		}

		$post = input('post.');
		$set = Db::name('admin_set')->where('aid', aid)->find();
		$jscode = input('post.code');
		$baiduapp = \app\common\System::appinfo(aid, 'baidu');
		$rs = request_post('https://spapi.baidu.com/oauth/jscode2sessionkey', ['code' => $jscode, 'client_id' => $baiduapp['appkey'], 'sk' => $baiduapp['appsecret']]);

		$rs = json_decode($rs, true);
		if (!$rs['openid']) {
			return $this->json(['status' => 0, 'msg' => $rs['error_description']]);
		}
		$openid = $rs['openid'];
		if ($openid) {
			$updata = [];
			$updata['baiduopenid'] = $openid;
			Db::name('member')->where('id', mid)->update($updata);
		}
		return json(['status' => 1, 'msg' => '更新成功']);
	}

	//微信小程序授权登录
	public function wxbaselogin() {
		$jscode = input('param.code');
		$fromid = input('param.pid');
		$wxapp = \app\common\System::appinfo(aid, 'wx');
		if ($wxapp['authtype'] == 1) {
			$url = 'https://api.weixin.qq.com/sns/component/jscode2session?appid=' . $wxapp['appid'] . '&component_appid=' . \app\common\Wechat::component_appid() . '&js_code=' . $jscode . '&grant_type=authorization_code&component_access_token=' . \app\common\Wechat::component_access_token();
		} else {
			$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $wxapp['appid'] . '&secret=' . $wxapp['appsecret'] . '&js_code=' . $jscode . '&grant_type=authorization_code';
		}
		$rs = request_get($url);
		$rs = json_decode($rs, true);
		if ($rs['errcode'] > 0) {
			return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($rs)]);
		}
		$openid = $rs['openid'];
		if (!$openid) {
			return json(['status' => 0, 'msg' => '获取授权信息失败']);
		}

		$unionid = $rs['unionid'];
		$session_key = $rs['session_key'];
		$member = Db::name('member')->where('aid', aid)->where(platform . 'openid', $openid)->find();
		if (!$member && $unionid) {
			$member = Db::name('member')->where('aid', aid)->where('unionid', $unionid)->find();
			if ($member) {
				Db::name('member')->where('id', $member['id'])->update([platform . 'openid' => $openid]);
			}

		}
		if (!$member) {
			$data = [];
			$data['aid'] = aid;
			$data[platform . 'openid'] = $openid;
			if ($unionid) {
				$data['unionid'] = $unionid;
			}
			$data['sex'] = 3;
			$data['nickname'] = '用户' . random(6);
			$data['headimg'] = PRE_URL . '/static/img/touxiang.png';
			$data['createtime'] = time();
			$data['last_visittime'] = time();
			//推广人
			if ($fromid) {
				$data['pid'] = $this->getpid($fromid);
			}
			$data['platform'] = platform;
			$mid = \app\model\Member::add(aid, $data);
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
			if ($data['pid']) {
				\app\common\Common::user_tjscore(aid, $mid);
			}

			//注册赠送
			\app\common\Common::registerGive(aid, array_merge($data, ['id' => $mid]));
		} else {
			$mid = $member['id'];
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->update([
				'mid' => $mid,
				'login_time' => time(),
			]);
		}
		cache($this->sessionid . '_mid', $mid, 7 * 86400);
		return $this->json(['status' => 1, 'msg' => '登录成功', 'mid' => $mid, 'session_id' => $this->sessionid]);

	}

	//发送验证码
	public function sendsms() {
		$code = rand(100000, 999999);
		$tel = input('post.tel');
		if (!preg_match("/^1[3456789]\d{9}$/", $tel)) {
			return $this->json(['status' => 0, 'msg' => '手机号格式错误']);
		}
//		Log::write('code:'.$code);
		cache($this->sessionid . '_smscode', md5($tel . '-' . $code), 600);
		cache($this->sessionid . '_smscodetimes', 0);
		$rs = \app\common\Sms::send(aid, $tel, 'tmpl_smscode', ['code' => $code]);
		return $this->json($rs);
	}

	//底部菜单
	public function gettabbardata() {
		$menuset = Db::name('designer_menu')->where('aid', aid)->where('platform', platform)->find();
		$menudata = json_decode($menuset['menudata'], true);
		$menulist = array();
		foreach ($menudata['list'] as $k => $v) {
			if ($k < $menuset['menucount']) {
				$menulist[] = $v;
			}
		}
		$menudata['list'] = $menulist;
		$indexurl = $menuset['indexurl'];
		if (platform == 'wx' && !input('post.fromw7')) {
			$menudata['list'] = [];
		}
		//内页菜单
		$menu2list = Db::name('designer_menu2')->where('aid', aid)->where('platform', 'wx')->where('status', 1)->order('id desc')->select()->toArray();
		$menu2datalist = [];
		if ($menu2list) {
			foreach ($menu2list as $k => $v) {
				$menu2data = [];
				$menu2data['backgroundColor'] = $v['backgroundColor'];
				$menu2data['indexurl'] = $v['indexurl'];
				$menu2data['list'] = json_decode($v['menudata'], true);
				$menulist = [];
				foreach ($menu2data['list'] as $k2 => $v2) {
					if ($k2 < $v['menucount']) {
						$menulist[] = $v2;
					}
				}
				$menu2data['list'] = $menulist;
				$menu2datalist[] = $menu2data;
			}
		}
		$textset = \think\Cache::get('textset_' . aid);
		return $this->json(['status' => 1, 'data' => $menudata, 'indexurl' => $indexurl, 'menu2data' => $menu2datalist, 'textset' => $textset]);
	}
	//绑定管理员会员ID
	public function bind() {
		$this->checklogin();
		$id = input('param.id/d');
		$token = input('param.token');
		if (!$token || $token != cache('adminbdtoken_' . $id)) {
			return $this->json(['status' => 0, 'msg' => '二维码已过期']);
		}
		Db::name('admin_user')->where('mid', mid)->update(['mid' => 0]);
		Db::name('admin_user')->where('aid', aid)->where('id', $id)->update(['mid' => mid]);
		$mpset = Db::name('admin_setapp_mp')->field('qrcode')->where('aid', aid)->find();
		cache($this->sessionid . '_uid', null);
		return $this->json(['status' => 1, 'msg' => '绑定成功', 'set' => $mpset]);
	}

	//领会员卡
	public function getcardurl() {
		$this->checklogin();
		$id = input('param.id/d');
		$membercard = Db::name('membercard')->where('id', $id)->find();
		if ($membercard && $membercard['ret_url']) {
			return redirect($membercard['ret_url']);
		}
	}

	//订阅消息
	public function subscribemessage() {
		if (mid && input('post.tmplid')) {
			$tmplid = input('post.tmplid');
			$tmplnum = Db::name('member_tmplnum')->where('aid', aid)->where('mid', mid)->where('tmplid', $tmplid)->find();
			if ($tmplnum) {
				Db::name('member_tmplnum')->where('id', $tmplnum['id'])->inc('num')->update();
			} else {
				Db::name('member_tmplnum')->insert(['aid' => aid, 'mid' => mid, 'tmplid' => $tmplid, 'num' => 1]);
			}
		}
		return $this->json([]);
	}
	public function captcha() {
		$captcha = new \app\common\Captcha();
		$picture = $captcha->create();
		$value = $captcha->captchaValue;
		cache($this->sessionid . '_captcha', $value, 3600);
		return $picture;
	}
	public function linked() {
		return $this->json(['status' => 1]);
	}

	public function getCustom() {
		return $this->json(['data' => getcustom()]);
	}

	public function agentCard() {
		$pid = input('param.pid/d');

		$info = $this->getAgentCard($pid);
		if ($info['pagecontent']) {
			$pagecontent = json_decode(\app\common\System::initpagecontent($info['pagecontent'], aid), true);
		}
		if (!$pagecontent) {
			$pagecontent = [];
		}

		$rdata = ['status' => 1];
		$rdata['info'] = $info ? $info : [];
		$rdata['pagecontent'] = $pagecontent;
		return $this->json($rdata);
	}

	private function getAgentCard($mid) {
		if (getcustom('agent_card')) {
			$sysset = Db::name('admin_set')->field('name,logo,desc,tel,address,longitude,latitude')->where('aid', aid)->find();
			if (mid > 0) {
				if ($this->member['pid'] > 0) {
					$pids = explode(',', $this->member['path']);
					$mid = $pids[0];
				} else {
					$count = \db('member_levelup_order')->where('aid', aid)->where('mid', mid)->where('status', 2)->count();
					if ($count) {
						$mid = mid;
					} else {
						$mid = 0;
					}

				}
			} else {
				if ($mid > 0) {
					$member = Db::name('member')->where('aid', aid)->where('id', $mid)->find();
					if ($member['pid'] > 0) {
						$pids = explode(',', $member['path']);
						$mid = $pids[0];
					} else {
						$count = \db('member_levelup_order')->where('aid', aid)->where('mid', $mid)->where('status', 2)->count();
						if ($count) {
							$mid = $member['id'];
						} else {
							$mid = 0;
						}

					}
				}
			}

			if (!$mid) {
				$mid = Db::name('admin_user')->where('aid', aid)->where('bid', 0)->where('isadmin', 'in', [1, 2])->value('mid');
			}

			if ($mid) {
				$info = Db::name('member_agent_card')->where('aid', aid)->where('mid', $mid)->find();
			}

			if (empty($info)) {
				$info = [
					'name' => '综合客服',
					'shopname' => $sysset['name'],
					'address' => $sysset['address'],
					'tel' => $sysset['tel'],
					'latitude' => $sysset['latitude'],
					'longitude' => $sysset['longitude'],
				];
			}
			$info['logo'] = $info['logo'] ? $info['logo'] : $sysset['logo'];
			$info['name'] = $info['name'] ? $info['name'] : '综合客服';
			return $info;
		}
	}
	//退出
	public function logout() {
		$rdata = [];
		$rdata['status'] = -3;
		$rdata['url'] = '/pages/index/index';
		if (mid) {
			Db::name('session')->where('aid', aid)->where('session_id', $this->sessionid)->delete();
			cache($this->sessionid . '_mid', null);
			$this->mid = 0;
			$this->sessionid = \think\facade\Session::getId();
			$rdata['sessionid'] = $this->sessionid;
		}
		return $this->json($rdata);
	}

	private function getpid($pid) {
		$newPid = 0;
		if ($pid <= 0) {
			return $newPid;
		}

		$upuser = Db::name('member')->where('id', intval($pid))->find();
		$uplv = Db::name('member_level')->where('aid', aid)->where('id', $upuser['levelid'])->find();
		//等级是否有分销权限
		if ($upuser && $uplv['can_agent'] != 0) {
			$newPid = $upuser['id'];
			//修改推荐人
			if (getcustom('update_member_pid')) {
				$set = Db::name('admin_set')->where('aid', aid)->find();
				if ($newPid == $set['pid_origin'] && $set['pid_new']) {
					$pidNewArr = explode(',', $set['pid_new']);
					$num = [];
					foreach ($pidNewArr as $k => $v) {
						$num[$k] = 0 + Db::name('member')->where('id', intval($v))->count();
					}
					$min = min($num);
					$key = array_search($min, $num);
					$newPid = $pidNewArr[$key];
				}
			}
		}
		return $newPid;
	}

	//$customdata['id'] //formid
	//$customdata['data'] //表单内容
	protected function customRegister($formdata = [], $formid = 0) {
		if (getcustom('register_fields')) {
			$form = Db::name('register_form')->where('aid', aid)->where('bid', bid)->find();
			if (empty($form) || empty($form['content'])) {
				return ['status' => 1, 'msg' => ''];
			}
			if ($form['id'] != $formid) {
				return ['status' => 0, 'msg' => '表单数据有误！'];
			}
			$formheader = [];
			if (empty($formdata)) {
				$formdata = [];
			}

			$data = [];
			$formcontent = json_decode($form['content'], true);
			foreach ($formcontent as $k => $v) {
				$value = $formdata['form' . $k];
				if (is_array($value)) {
					$value = implode(',', $value);
				}
				if ($v['key'] == 'switch') {
					if ($value) {
						$value = '是';
					} else {
						$value = '否';
					}
				}
				$data['form' . $k] = strval($value);
				if ($v['val3'] == 1 && $data['form' . $k] === '') {
					return ['status' => 0, 'msg' => $v['val1'] . ' 必填' . $data['form' . $k]];
				}
			}
			if ($data) {
				$data['aid'] = aid;
				$data['formid'] = $formid;
				$data['content'] = $form['content'];
				$data['createtime'] = time();
				$data['bid'] = bid;
				$recordid = Db::name('register_form_record')->insertGetId($data);
				return ['status' => 1, 'msg' => '自定义表单保存成功', 'recordid' => $recordid];
			} else {
				return ['status' => 1, 'msg' => ''];
			}
		}
		return ['status' => 1, 'msg' => ''];
	}

	public function get_area_mendain() {
		if (getcustom('xixie')) {
			//获取地址信息及门店信息
			if (request()->isPost()) {

				$key = 'ABLBZ-4BIKU-GFTVB-BK7IK-OLQ35-QCBFF';
				$post = input('post.');

				if (!$post['latitude'] || !$post['longitude']) {
					return $this->json(['status' => 0, 'msg' => '请授权获取地理位置']);
				}

				$latitude = $post['latitude'];
				$longitude = $post['longitude'];

				$data = [];

				$data['latitude'] = $latitude;
				$data['longitude'] = $longitude;
				$data['address'] = '';
				$data['province'] = '';
				$data['city'] = '';
				$data['district'] = '';
				$data['mendian'] = '';

				$province = '';
				$city = '';
				//通过坐标获取省市区
				$url = 'https://apis.map.qq.com/ws/geocoder/v1/?key=' . $key . '&location=' . $latitude . ',' . $longitude;
				$res = json_decode(request_get($url), true);
				if ($res && $res['status'] == 0) {
					$address_component = $res['result']['address_component'];
					$data['address'] = $res['result']['address'];
					$data['province'] = $address_component['province'];
					$data['city'] = $address_component['city'];
					$data['district'] = $address_component['district'];

					$province = $data['province'];
					$city = $data['city'];
				}
				$data['mendian']['m_address'] = '';
				if ($this->member) {
					$m_address = Db::name('member_address')
						->where('mid', mid)
						->where('aid', aid)
						->order('isdefault desc,id desc')
						->field('id,area,address')
						->find();
					if ($m_address) {
						$data['mendian']['m_address'] = $m_address['area'] . ' ' . $m_address['address'];
						$province = $m_address['province'];
						$city = $m_address['city'];
						$longitude = $m_address['longitude'];
						$latitude = $m_address['latitude'];
					}
				}
				if ($province && $city) {
					//查询此城市区域是否开放
					$where = [];
					$where[] = Db::raw("find_in_set('" . $province . "',province)");
					$where[] = Db::raw("find_in_set('" . $city . "',city)");
					$count_area = Db::name('open_area')
						->where($where)
						->count();
					if ($count_area) {
						if ($longitude && $latitude) {
							//处理门店是否在他服务范围内
							$deal_mendian = $this->deal_mendian($longitude, $latitude, $province, $city);
							if ($deal_mendian) {
								$data['mendian'] = $deal_mendian['mendian'];
							}
						}
					}
				}
				//查询用户的地址
				return $this->json(['status' => 1, 'data' => $data]);
			}
		}
	}

	public function bind_wxtel() {
		if (getcustom('xixie')) {
			//绑定微信手机号
			if (request()->isPost()) {
				if (input('param.code') && input('post.iv') && input('post.encryptedData')) {
					$jscode = input('param.code');
					$encryptedData = input('post.encryptedData');
					$iv = input('post.iv');

					$wxapp = \app\common\System::appinfo(aid, 'wx');
					if ($wxapp['authtype'] == 1) {
						$url = 'https://api.weixin.qq.com/sns/component/jscode2session?appid=' . $wxapp['appid'] . '&component_appid=' . \app\common\Wechat::component_appid() . '&js_code=' . $jscode . '&grant_type=authorization_code&component_access_token=' . \app\common\Wechat::component_access_token();
					} else {
						$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $wxapp['appid'] . '&secret=' . $wxapp['appsecret'] . '&js_code=' . $jscode . '&grant_type=authorization_code';
					}
					$rs = request_get($url);
					$rs = json_decode($rs, true);
					if ($rs['errcode'] > 0) {
						return $this->json(['status' => 0, 'msg' => \app\common\Wechat::geterror($rs)]);
					}
					$session_key = $rs['session_key'];
					if (!$session_key) {
						return json(['status' => 0, 'msg' => '获取授权信息失败']);
					}

					$pc = new \app\common\WxBizDataCrypt($wxapp['appid'], $session_key);
					$errCode = $pc->decryptData($encryptedData, $iv, $rdata);
					$rdata = json_decode($rdata, true);

					if ($rdata['phoneNumber']) {
						return json(['status' => 1, 'data' => $rdata['phoneNumber']]);
					} else {
						return json(['status' => 0, 'msg' => '授权获取手机号失败']);
					}
				} else {
					return json(['status' => 0, 'msg' => '授权获取手机号失败']);
				}
			}
		}
	}
	//处理服务门店
	public function deal_mendian($longitude, $latitude, $province, $city, &$id_str = '') {
		if (getcustom('xixie')) {
			$data = [];
			$data['mendian'] = '';

			$where = [];
			$where[] = ['province', '=', $province];
			$where[] = ['city', '=', $city];
			$where[] = ['aid', '=', aid];
			if ($id_str) {
				$where[] = ['id', 'not in', $id_str];
			}
			$where[] = ['status', '=', 1];
			$where[] = ['longitude', '<>', ''];
			$where[] = ['latitude', '<>', ''];

			//查询门店
			$order = Db::raw("({$longitude}-longitude)*({$longitude}-longitude) + ({$latitude}-latitude)*({$latitude}-latitude) ");
			$mendian = Db::name('mendian')
				->where($where)
				->order($order)
				->find();

			if ($mendian) {
				if ($mendian['peisong_rangetype'] == 1) {
					$pspointsArr = explode(';', $mendian['peisong_rangepath']);
					$pspoints = [];
					foreach ($pspointsArr as $pspoint) {
						$pspointArr = explode(',', $pspoint);
						$pspoints[] = ['lat' => $pspointArr[1], 'lng' => $pspointArr[0]];
					}
					if ($pspoints) {
						$rs = \app\model\Freight::is_point_in_polygon(['lat' => $longitude, 'lng' => $latitude], $pspoints);
						if ($rs) {
							$data['mendian'] = $mendian;
						} else {
							$id_str .= $id_str ? ',' . $mendian['id'] : $mendian['id'];
							$deal_mendian = $this->deal_mendian($longitude, $latitude, $province, $city, $id_str);
							if ($deal_mendian && $deal_mendian['mendian']) {
								$data['mendian'] = $deal_mendian['mendian'];
							}
						}
					}
					$juli = getdistance($longitude, $latitude, $mendian['peisong_lng2'], $mendian['peisong_lat2'], 1);
				} else {
					$juli = getdistance($longitude, $latitude, $mendian['peisong_lng'], $mendian['peisong_lat'], 1);

					if ($juli <= $mendian['peisong_range']) {
						$data['mendian'] = $mendian;
					} else {
						$id_str .= $id_str ? ',' . $mendian['id'] : $mendian['id'];
						$deal_mendian = $this->deal_mendian($longitude, $latitude, $province, $city, $id_str);
						if ($deal_mendian && $deal_mendian['mendian']) {
							$data['mendian'] = $deal_mendian['mendian'];
						}
					}
				}
			}
			return $data;
		}
	}
	public function checkGotoLink() {
		$with_system_param = 0;
		if (getcustom('with_system_param')) {
			$admin = Db::name('admin')->where('id', aid)->find();
			if ($admin && $admin['with_system_param'] == 1) {
				$with_system_param = 1;
			}
		}
		return $this->json(['status' => 1, 'with_system_param' => $with_system_param]);
	}
}